package com.dl7.mvp.module.home;

import android.Manifest;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.util.SparseArray;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.dl7.downloaderlib.FileDownloader;
import com.dl7.mvp.R;
import com.dl7.mvp.ad.Constants;
import com.dl7.mvp.module.base.BaseActivity;
import com.dl7.mvp.module.video.main.VideoMainFragment;
import com.dl7.mvp.utils.SnackbarUtils;
import com.qq.e.ads.banner.ADSize;
import com.qq.e.ads.banner.AbstractBannerADListener;
import com.qq.e.ads.banner.BannerView;
import com.qq.e.comm.util.AdError;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import rx.functions.Action1;

/**
 * 程序入口
 */
public class HomeActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {
    // ====== ad ======
    @BindView(R.id.bannerContainer)
    ViewGroup mBannerContainer;
    BannerView mBannerView;
    // ====== ad ======
    private long mExitTime = 0;

    ArrayList<Fragment> mFragmentList = new ArrayList<>();
    ArrayList<String> mTitleList = new ArrayList<>();

    @BindView(R.id.radio_group)
    RadioGroup mRadioGroup;
    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_home;
    }

    @Override
    protected void initInjector() {
    }

    @Override
    protected void initViews() {
        //mSparseTags.put(R.id.nav_videos, "Videos");
        mRadioGroup.setOnCheckedChangeListener(this);
        _getPemission();
        _initBanner();
        // mBannerView.loadAD();
    }

    @Override
    protected void updateViews() {
        mFragmentList.add(new VideoMainFragment());
        mTitleList.add("Video");
        mFragmentList.add(new VideoMainFragment());
        mTitleList.add("music");
        mFragmentList.add(new VideoMainFragment());
        mTitleList.add("mine");
        //初始化要显示的Fragment数组
        //获取Fragment管理器
        FragmentManager manager = getSupportFragmentManager();
        //获取事物(使用v4包下)
        FragmentTransaction transaction = manager.beginTransaction();
        //默认选中第一页
        transaction.replace(R.id.fl_radio_show, mFragmentList.get(0));
        //提交事物
        transaction.commit();
        //默认点击首页
        mRadioGroup.check(R.id.radio_video);
    }

    @Override
    public void onBackPressed() {
        _exit();
    }

    private void _getPemission() {
        final File dir = new File(FileDownloader.getDownloadDir());
        if (!dir.exists() || !dir.isDirectory()) {
            dir.delete();
            new RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                    .subscribe(new Action1<Boolean>() {
                        @Override
                        public void call(Boolean granted) {
                            if (granted) {
                                dir.mkdirs();
                            } else {
                                SnackbarUtils.showSnackbar(HomeActivity.this, "下载目录创建失败", true);
                            }
                        }
                    });
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        //写法与默认点击页面的相同
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        switch (checkedId) {
            case R.id.radio_video:
                transaction.replace(R.id.fl_radio_show, mFragmentList.get(0));
                break;
            case R.id.radio_music:
                transaction.replace(R.id.fl_radio_show, mFragmentList.get(1));
                break;
            case R.id.radio_mine:
                transaction.replace(R.id.fl_radio_show, mFragmentList.get(2));
                break;
        }
        transaction.commit();
    }

    /**
     * 退出
     */
    private void _exit() {
        if (System.currentTimeMillis() - mExitTime > 2000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private void _initBanner() {
        this.mBannerView = new BannerView(this, ADSize.BANNER, Constants.APPID, Constants.BannerPosID);
        // 注意：如果开发者的banner不是始终展示在屏幕中的话，请关闭自动刷新，否则将导致曝光率过低。
        // 并且应该自行处理：当banner广告区域出现在屏幕后，再手动loadAD。
        mBannerView.setRefresh(30);
        mBannerView.setADListener(new AbstractBannerADListener() {

            @Override
            public void onNoAD(AdError error) {
                Log.i("AD_DEMO", String.format("Banner onNoAD，eCode = %d, eMsg = %s", error.getErrorCode(), error.getErrorMsg()));
            }

            @Override
            public void onADReceiv() {
                Log.i("AD_DEMO", "ONBannerReceive");
            }
        });
        mBannerContainer.addView(mBannerView);
    }

}
